package cn.gudian.cms.Stat

class StatController {
  private static List list = new ArrayList();
  // def index = { redirect(action: "list", params: params) }
  def index = {
    def s = request.getHeader("REFERER") //取得调用页面的地址
    def ser = request.getServerName()  //取得当前的域名
    if (s == null || s.indexOf(ser) < 0) {
      render """
          document.write('非法请求');
        """
      return
    }
    if (!params.mode && !Stat.modes.any {it.equals(params.mode) } && !params.modeID) {
      render """
          document.write('非法模块');
        """
      return
    }

    def statInstance = Stat.findByModeAndModeID(params.mode, params.modeID)
    def num = 1
    if (statInstance) {
      num = statInstance.vnumber

    }
    render """
            document.write("${num}")
           """


    saveList(params.mode, params.modeID);

  }

  public static void saveList(key, value) {
    list.add([key, value]);
    if (list.size() >= 10) {
      List listClone = new ArrayList();
      listClone = list.clone();//复制一份list用来进行数据处理
      list = new ArrayList();
      Map map = new HashMap();
      for (Object o: listClone) {
        map.put(o, map.get(o) == null ? 1 : map.get(o) + 1);
      }
      map.each {
        def k = it
        def statInstance = Stat.findByModeAndModeID(k.key[0], Integer.parseInt(k.key[1]));
        if (!statInstance) {
          statInstance = new Stat();
          statInstance.mode = k.key[0];
          statInstance.modeID = Integer.parseInt(k.key[1]);
          statInstance.vnumber = k.value;
          statInstance.save();
        } else {
          statInstance.vnumber = statInstance.vnumber + k.value;
          statInstance.save();
        }
      }
    }
  }
// the delete, save and update actions only accept POST requests
  static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

  def list = {
    params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    [statInstanceList: Stat.list(params), statInstanceTotal: Stat.count()]
  }

  def create = {
    def statInstance = new Stat()
    statInstance.properties = params
    return [statInstance: statInstance]
  }

  def save = {
    def statInstance = new Stat(params)
    if (!statInstance.hasErrors() && statInstance.save()) {
      flash.message = "stat.created"
      flash.args = [statInstance.id]
      flash.defaultMessage = "Stat ${statInstance.id} created"
      redirect(action: "show", id: statInstance.id)
    }
    else {
      render(view: "create", model: [statInstance: statInstance])
    }
  }

  def show = {
    def statInstance = Stat.get(params.id)
    if (!statInstance) {
      flash.message = "stat.not.found"
      flash.args = [params.id]
      flash.defaultMessage = "Stat not found with id ${params.id}"
      redirect(action: "list")
    }
    else {
      return [statInstance: statInstance]
    }
  }

  def edit = {
    def statInstance = Stat.get(params.id)
    if (!statInstance) {
      flash.message = "stat.not.found"
      flash.args = [params.id]
      flash.defaultMessage = "Stat not found with id ${params.id}"
      redirect(action: "list")
    }
    else {
      return [statInstance: statInstance]
    }
  }

  def update = {
    def statInstance = Stat.get(params.id)
    if (statInstance) {
      if (params.version) {
        def version = params.version.toLong()
        if (statInstance.version > version) {

          statInstance.errors.rejectValue("version", "stat.optimistic.locking.failure", "Another user has updated this Stat while you were editing")
          render(view: "edit", model: [statInstance: statInstance])
          return
        }
      }
      statInstance.properties = params
      if (!statInstance.hasErrors() && statInstance.save()) {
        flash.message = "stat.updated"
        flash.args = [params.id]
        flash.defaultMessage = "Stat ${params.id} updated"
        redirect(action: "show", id: statInstance.id)
      }
      else {
        render(view: "edit", model: [statInstance: statInstance])
      }
    }
    else {
      flash.message = "stat.not.found"
      flash.args = [params.id]
      flash.defaultMessage = "Stat not found with id ${params.id}"
      redirect(action: "edit", id: params.id)
    }
  }

  def delete = {
    def statInstance = Stat.get(params.id)
    if (statInstance) {
      try {
        statInstance.delete()
        flash.message = "stat.deleted"
        flash.args = [params.id]
        flash.defaultMessage = "Stat ${params.id} deleted"
        redirect(action: "list")
      }
      catch (org.springframework.dao.DataIntegrityViolationException e) {
        flash.message = "stat.not.deleted"
        flash.args = [params.id]
        flash.defaultMessage = "Stat ${params.id} could not be deleted"
        redirect(action: "show", id: params.id)
      }
    }
    else {
      flash.message = "stat.not.found"
      flash.args = [params.id]
      flash.defaultMessage = "Stat not found with id ${params.id}"
      redirect(action: "list")
    }
  }

  def deleteAll = {
    def qstr = params.qstr
    if (qstr) {
      try {
        Stat.executeUpdate("delete Stat where id in(" + qstr + ")")
        flash.message = "delete successfully:" + qstr
        redirect(action: "list")
      } catch (Exception e) {
        flash.message = "delete failed:" + qstr
        redirect(action: "list")
      }
    }
  }
}
